package cn.lnexin.file;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 替换文件中的特定字符
 * @Description:TODO
 * @author	Daniel
 * @date	2017年12月22日 下午6:31:45
 */
public class BatchReplaceStr {
	static String dir = "E:/work/01.02/log";
	//源字符
	static String str_src = "2018-01-02";
	
	//要替换为的目标字符
	static String str_tar = "2018-01-01";
	
	//文件名过滤
	static String filter_str = "2018-01-01";
	
	public static void main(String[] args) throws IOException {
		// 拿到待修改文件列表
		List<String> fileList = FileUtil.getFileList(dir);
		
		for (String fielN : fileList) {
			if (!fielN.contains(filter_str)) continue;
			
			List<String> result = new ArrayList<>();
			BufferedReader reader = FileUtil.getTxtReader(fielN);
			String line = "";
			while ((line = reader.readLine()) != null) {
				line = replaceStr(line);
				result.add(line);
			}
			outFile(fielN, result);
		}
	}
	
	private static void outFile(String fileName, List<String> result) throws IOException {
		StringBuffer sb = new StringBuffer();
		for (String string : result) {
			sb.append(string).append("\n");
		}
		FileOutputStream fos = new FileOutputStream(fileName);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		osw.write(sb.toString());
		osw.close();
		fos.close();
		System.out.println("文件输出完成:" + fileName);
	}
	
	protected static String replaceStr(String line) {
		line = line.replace(str_src, str_tar);
		return line;
	}
	
}
